﻿using Newtonsoft.Json;
using NLog.Internal;
using Stock.Client.Schedule;
using Stock.Client.Service;
using Stock.Client.Utils;
using Stock.Model.DB;
using Stock.Model.MR;
using Stock.Model.WX;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace Stock.Client
{
    public partial class frmMain : Form
    {
        private bool isShow = false;
        IList<TStock> stocks = null;
        IList<TStockSchedule> stockSchedules = null;//监控

        public frmMain()
        {
            InitializeComponent();
        }

        #region 事件


        private void frmMain_Load(object sender, EventArgs e)
        {
            this.ShowInTaskbar = isShow = false;
            this.Hide();

            //this.WindowState = FormWindowState.Minimized;
            InitData();
            ScheduleHelper.Start();
            timer1.Start();
        }


        private void btnWorkDay_Click(object sender, EventArgs e)
        {
            string year = cbWorkYear.Text == "" ? DateTime.Now.Year.ToString() : cbWorkYear.Text;
            string month = cbWorkMonth.Text == "" ? DateTime.Now.Month.ToString("00") : cbWorkMonth.Text;
            try
            {
                DateUtils.GetHolidays(year, month);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            MessageBox.Show("操作完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            menuShow_Click(sender, e);
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            notifyIcon1.Dispose();
        }

        private void menuHolidays_Click(object sender, EventArgs e)
        {
            btnWorkDay_Click(sender, e);
        }

        private void menuExit_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            BindingPrice();
        }

        private void menuShow_Click(object sender, EventArgs e)
        {
            if (isShow == false)
            {
                this.Show();
                this.ShowInTaskbar = isShow = true;
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.Hide();
                this.ShowInTaskbar = isShow = false;
                this.WindowState = FormWindowState.Minimized;
            }

        }

        private void txtCode_TextChanged(object sender, EventArgs e)
        {
            if (txtHistoryCode.TextLength == 6)
            {
                string code = PublicUtils.GetPrefixCode(txtHistoryCode.Text);
                string name = Tencent_Service.GetStockBaseInfoAsync("s_" + code).Result;
                if (!string.IsNullOrEmpty(name) && name.Split('~').Length > 2)
                    lblHistoryStockName.Text = name.Split('~')[1];
            }
        }



        private void gvStocks_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 7 || e.ColumnIndex == 8)
            {
                int id = Convert.ToInt32(gvStocks[0, e.RowIndex].Value);
                bool isWXAlert = false;
                bool isTrading = Convert.ToBoolean(gvStocks[3, e.RowIndex].Value);
                bool isAlert = Convert.ToBoolean(gvStocks[4, e.RowIndex].Value);
                string remark = gvStocks[5, e.RowIndex].Value.ToString();
                if (e.ColumnIndex == 7)//编辑
                {
                    Tencent_Service.UpdateStock(id, isTrading, isAlert, isWXAlert, remark);
                }
                if (e.ColumnIndex == 8)//删除
                {
                    if (MessageBox.Show("是否确认删除?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        Tencent_Service.DelStock(id);
                        this.tStockBindingSource.DataSource = Tencent_Service.GetStockList();
                        MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }


        private void btnAddStock_Click(object sender, EventArgs e)
        {
            if (txtAddCode.TextLength == 6)
            {
                TStock stock = new TStock()
                {
                    CODE = txtAddCode.Text,
                    IS_ALERT = chkAlert.Checked,
                    IS_TRADING = chkTrading.Checked,
                    IS_WEIXIN_ALERT = chkWX.Checked,
                    NAME = lblAddName.Text,
                    PREFIX = PublicUtils.GetPrefix(txtAddCode.Text),
                    REMARKS = ""
                };
                if (Tencent_Service.InsertStock(stock))
                    MessageBox.Show("新增成功", "提示");
                else
                    MessageBox.Show("新增失败", "提示");
                stocks = Tencent_Service.GetStockList();
                this.tStockBindingSource.DataSource = stocks;
            }
            else
            {
                MessageBox.Show("请输入正确的代码", "提示");
            }
        }

        private void btnChannelSave_Click(object sender, EventArgs e)
        {
            TStockChannel stockChannel = new TStockChannel()
            {
                CODE = lblModelStockCode.Text,
                NAME = cbModelStockName.Text,
                POINT_A = txtAPrice.Value,
                POINT_A_DATE = dtADate.Value,
                POINT_B = txtBPrice.Value,
                POINT_B_DATE = dtBDate.Value,
                POINT_C = txtCPrice.Value,
                POINT_C_DATE = dtCDate.Value,
                DATE_INTERVAL = Tencent_Service.GetHolidaysCount(dtADate.Value, dtCDate.Value, Tencent_Service.diffResultFormat.dd)
            };
            if (Tencent_Service.InsertChannel(stockChannel))
                MessageBox.Show("新增成功", "提示");
            else
                MessageBox.Show("新增失败", "提示");
            stockSchedules = Tencent_Service.GetStockSchedule();
            this.tStockChannelBS.DataSource = Tencent_Service.GetStockChannels();
        }

        private void cbChennalName_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cbModelStockName.SelectedValue != null)
                lblModelStockCode.Text = ((TStock)cbModelStockName.SelectedValue).CODE;
        }


        private void btnInsertEnclosure_Click(object sender, EventArgs e)
        {
            TStockEnclosure stockEnclosure = new TStockEnclosure()
            {
                CODE = lblModelStockCode.Text,
                NAME = cbModelStockName.Text,
                POINT_UP = numEnclosureUp.Value,
                POINT_UP_DATE = dtEnclosureDateUp.Value,
                POINT_DOWN = numEnclosureDown.Value,
                POINT_DOWN_DATE = dtEnclosureDateDown.Value
            };
            if (Tencent_Service.InsertEnclosure(stockEnclosure))
                MessageBox.Show("新增成功", "提示");
            else
                MessageBox.Show("新增失败", "提示");
            stockSchedules = Tencent_Service.GetStockSchedule();
            this.tStockEnclosureBS.DataSource = Tencent_Service.GetStockEnclosures();
        }

        private void btnInsertTriangle_Click(object sender, EventArgs e)
        {
            TStockTriangle stockTriangle = new TStockTriangle()
            {
                CODE = lblModelStockCode.Text,
                NAME = cbModelStockName.Text,
                POINT_DOWN_A1 = numPointDownA1.Value,
                POINT_DOWN_A1_DATE = dtDateDownA1.Value,
                POINT_DOWN_A2 = numPointDownA2.Value,
                POINT_DOWN_A2_DATE = dtDateDownA2.Value,
                POINT_UP_A1 = numPointUpA1.Value,
                POINT_UP_A1_DATE = dtDateUpA1.Value,
                POINT_UP_A2 = numPointUpA2.Value,
                POINT_UP_A2_DATE = dtDateUpA2.Value
            };
            if (Tencent_Service.InsertTriangle(stockTriangle))
                MessageBox.Show("新增成功", "提示");
            else
                MessageBox.Show("新增失败", "提示");
            stockSchedules = Tencent_Service.GetStockSchedule();
            this.tStockTriangleBS.DataSource = Tencent_Service.GetStockTriangles();
        }



        private void btnHistoryAdd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtHistoryCode.Text))
            {
                MessageBox.Show("请输入代码", "提示");
                return;
            }
            DateTime start = dtHistoryS.Value;
            DateTime end = dtHistoryE.Value;
            if (start > end)
            {
                MessageBox.Show("起始年月日不可大于截止年月日", "提示");
                return;
            }
            string stockHistory = DateUtils.GetStock_History_Tencent(start, end, txtHistoryCode.Text);
            new Thread(() =>
            {
                Tencent_Service.GetTStockHistory(stockHistory, PublicUtils.GetPrefixCode(txtHistoryCode.Text), lblHistoryStockName.Text);
            });
        }


        private void txtAddCode_TextChanged(object sender, EventArgs e)
        {
            if (txtAddCode.TextLength == 6)
            {
                string code = PublicUtils.GetPrefixCode(txtAddCode.Text);
                string name = Tencent_Service.GetStockBaseInfoAsync("s_" + code).Result;
                if (!string.IsNullOrEmpty(name) && name.Split('~').Length > 2)
                    lblAddName.Text = name.Split('~')[1];
            }
        }

        private void cbModelStockName_SelectedValueChanged(object sender, EventArgs e)
        {
            TStock stock = (TStock)cbModelStockName.SelectedItem;
            if (stock == null)
                return;
            lblModelStockCode.Text = stock.CODE;

        }

        private void btnCalculateForm_Click(object sender, EventArgs e)
        {
            Tencent_Service.InsertStockSchedule();
            MessageBox.Show("保存成功", "提示");
        }


        /// <summary>
        /// 通道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvChannel_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;
            int id = Convert.ToInt32(gvChannel[0, e.RowIndex].Value);
            //更新
            if (e.ColumnIndex == 9)
            {
                TStockChannel stockChannel = (TStockChannel)gvChannel.CurrentRow.DataBoundItem;
                Tencent_Service.UpdateChannel(stockChannel);
            }
            //删除
            if (e.ColumnIndex == 10)
            {
                Tencent_Service.DelChannel(id);
                gvChannel.Rows.RemoveAt(e.RowIndex);
            }
        }


        private void gvEnclosure_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;
            int id = Convert.ToInt32(gvEnclosure[0, e.RowIndex].Value);
            //更新
            if (e.ColumnIndex == 7)
            {
                TStockEnclosure newStockEnclosure = (TStockEnclosure)gvEnclosure.CurrentRow.DataBoundItem;
                Tencent_Service.UpdateEnclosure(newStockEnclosure);
            }
            //删除
            if (e.ColumnIndex == 8)
            {
                Tencent_Service.DelEnclosure(id);
                gvEnclosure.Rows.RemoveAt(e.RowIndex);
            }

        }

        private void gvTriangle_CellClick(object sender, DataGridViewCellEventArgs e)
        {

            if (e.RowIndex == -1)
                return;
            int id = Convert.ToInt32(gvTriangle[0, e.RowIndex].Value);
            //更新
            if (e.ColumnIndex == 11)
            {
                TStockTriangle stockTriangle = (TStockTriangle)gvTriangle.CurrentRow.DataBoundItem;
                Tencent_Service.UpdateTriangle(stockTriangle);
            }
            //删除
            if (e.ColumnIndex == 12)
            {
                Tencent_Service.DelTriangle(id);
                gvTriangle.Rows.RemoveAt(e.RowIndex);
            }
        }

        #region 麦蕊网



        private void txtMrCode_TextChanged(object sender, EventArgs e)
        {
            if (txtMRCode.Text.Length == 6)
            {
                string code = PublicUtils.GetPrefixCode(txtMRCode.Text);
                string name = Tencent_Service.GetStockBaseInfoAsync("s_" + code).Result;
                if (!string.IsNullOrEmpty(name) && name.Split('~').Length > 2)
                    lblMRName.Text = name.Split('~')[1];
            }
        }

        private void btnSendAPI_Click(object sender, EventArgs e)
        {
            string[] chk = chkAPIs.EditValue.ToString().Split(',');
            string address = string.Empty, url = string.Empty;
            string token = System.Configuration.ConfigurationManager.AppSettings["MR_token"];

            foreach (string s in chk)
            {
                url = string.Format(System.Configuration.ConfigurationManager.AppSettings[s], cmbMRYear.Text, cmbMRQuarter.Text, token);
                string result = MR_Service.GetSend(url).Result;

                switch (s)
                {
                    case "MR_Profitability":
                        List<MR_Profitability> mr = JsonConvert.DeserializeObject<List<MR_Profitability>>(result);
                        break;
                    case "MR_AbilityToOperate":
                        break;
                    case "MR_GrowthAbility":
                        break;
                    case "MR_Debt_Paying_Ability":
                        break;
                    case "MR_The_Cash_Flow":
                        break;
                    case "MR_Performance_Report":
                        break;
                }
            }
        }


        #endregion

        #endregion

        #region 私有方法


        private void InitData()
        {
            cbWorkYear.Items.Clear();
            for (int i = -1; i < 3; i++)
                cbWorkYear.Items.Add(DateTime.Now.Year + i);

            cbWorkMonth.Items.Clear();
            for (int i = 1; i <= 12; i++)
            {
                cbWorkMonth.Items.Add(i.ToString("00"));
            }
            InitGridView();
            dtHistoryS.Value = DateTime.Now.AddYears(-1);
            dtHistoryE.Value = DateTime.Now;

            //生成当日的交易计划
            Tencent_Service.InsertStockSchedule();
            //获取当日交易计划
            stockSchedules = Tencent_Service.GetStockSchedule();

            stocks = Tencent_Service.GetStockList();
            this.tStockBindingSource.DataSource = stocks;

            Tencent_Service.ClearStockLog();

            #region 麦蕊网


            for (int i = 0; i < 10; i++)
                cmbMRYear.Properties.Items.Add(DateTime.Now.Year - i);


            #endregion
        }


        private void InitGridView()
        {
            //列表
            stocks = Tencent_Service.GetStockList();
            this.tStockBindingSource.DataSource = stocks;
            gvStocks.Columns[0].Visible = false;
            gvStocks.AutoGenerateColumns = false;
            gvStocks.DataSource = this.tStockBindingSource;

            //通道列表
            this.tStockChannelBS.DataSource = Tencent_Service.GetStockChannels();
            gvChannel.Columns[0].Visible = false;
            gvChannel.AutoGenerateColumns = false;
            gvChannel.DataSource = this.tStockChannelBS;

            //箱体列表
            this.tStockEnclosureBS.DataSource = Tencent_Service.GetStockEnclosures();
            gvEnclosure.Columns[0].Visible = false;
            gvEnclosure.AutoGenerateColumns = false;
            gvEnclosure.DataSource = this.tStockEnclosureBS;

            //三角
            this.tStockTriangleBS.DataSource = Tencent_Service.GetStockTriangles();
            gvTriangle.Columns[0].Visible = false;
            gvTriangle.AutoGenerateColumns = false;
            gvTriangle.DataSource = this.tStockTriangleBS;
        }



        /// <summary>
        /// 显示当前报价
        /// </summary>
        private void BindingPrice()
        {
            if (combStockList.SelectedItem == null)
                return;
            TStock stock = (TStock)combStockList.SelectedItem;
            if (stock == null || string.IsNullOrEmpty(stock.CODE))
                return;
            this.PriceBindingSource.DataSource = Tencent_Service.GetCurrentStockPrice(stock.CODE);

            CheckAlterMessage();
        }

        private void CheckAlterMessage()
        {
            string codes = string.Empty;
            List<string> WXmsg = new List<string>();
            List<string> Alertmsg = new List<string>();
            stocks.ToList().ForEach(o => codes += o.CODE + ",");
            if (codes.Length > 0)
                codes = codes.Substring(0, codes.Length - 1);
            List<TStockLog> stockLogs = Tencent_Service.GetCurrentStocksPrice(codes).ToList();
            //检查书否触发交易计划
            TStockSchedule[] stockSchedule1 = new TStockSchedule[stockSchedules.Count];
            stockSchedules.CopyTo(stockSchedule1, 0);
            foreach (TStockSchedule stockSchedule in stockSchedule1)
            {
                TStock stock = stocks.FirstOrDefault(o => o.CODE == stockSchedule.CODE);
                //if (stock.IS_WEIXIN_ALERT == true)
                TStockLog log = stockLogs.FirstOrDefault(o => o.CODE == stockSchedule.CODE);
                if (log != null)
                {
                    if (stockSchedule.TRADING == "S" && log.CLOSE >= stockSchedule.PRICE)
                    {
                        if (stock.IS_WEIXIN_ALERT == true)
                            WXmsg.Add(string.Format("{0} {1} 触发了卖出预警。预警价格：{2}，\r\n当前价格：{3} 。", stockSchedule.CODE,
                                  stockSchedule.NAME, stockSchedule.PRICE, log.CLOSE));
                        if (stock.IS_ALERT == true)
                            Alertmsg.Add(string.Format("{0} {1} 触发了卖出预警。预警价格：{2}，\r\n当前价格：{3} 。", stockSchedule.CODE,
                                  stockSchedule.NAME, stockSchedule.PRICE, log.CLOSE));

                        Tencent_Service.UpdateStockSchedule(stockSchedule.ID);
                    }
                    else if (stockSchedule.TRADING == "B" && log.CLOSE <= stockSchedule.PRICE)
                    {
                        if (stock.IS_WEIXIN_ALERT == true)
                            WXmsg.Add(string.Format("{0} {1} 触发了买入预警。预警价格：{2} ，\r\n当前价格：{3} 。", stockSchedule.CODE,
                                  stockSchedule.NAME, stockSchedule.PRICE, log.CLOSE));
                        if (stock.IS_ALERT == true)
                            Alertmsg.Add(string.Format("{0} {1} 触发了买入预警。预警价格：{2} ，\r\n当前价格：{3} 。", stockSchedule.CODE,
                                  stockSchedule.NAME, stockSchedule.PRICE, log.CLOSE));
                        Tencent_Service.UpdateStockSchedule(stockSchedule.ID);
                    }
                }
                stockSchedules.Remove(stockSchedule);
            }


            if (WXmsg.Count > 0)
            {
                //发微信
                WXService.SendMessage(WXmsg);
            }
            if (Alertmsg.Count > 0)
            {

                //弹出右下角
                foreach (string m in Alertmsg)
                {
                    frmMessage frmShowWarning = new frmMessage(m);//Form1为要弹出的窗体（提示框），
                    Point p = new Point(Screen.PrimaryScreen.WorkingArea.Width - frmShowWarning.Width, Screen.PrimaryScreen.WorkingArea.Height);
                    frmShowWarning.PointToScreen(p);
                    frmShowWarning.Location = p;
                    frmShowWarning.Show();
                    for (int i = 0; i <= frmShowWarning.Height; i++)
                    {
                        frmShowWarning.Location = new Point(p.X, p.Y - i);
                        //Thread.Sleep(10);//将线程沉睡时间调的越小升起的越快
                    }
                }


            }
        }




        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            string message = @"
<xml>
<ToUserName><![CDATA[oegRb5uO91RtXcc148bnJxEdpALo]]></ToUserName>
<FromUserName><![CDATA[oegRb5uO91RtXcc148bnJxEdpALo]]></FromUserName>
<CreateTime>637770841085817631</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[欢迎使用微信公共账号，您输入的内容为：111938]]></Content>
</xml> 
";

            string json = "{\"URL\":\"http://zjstock.free.aeert.com/api/GetTextMessage\",\"ToUserName\":\"oegRb5uO91RtXcc148bnJxEdpALo\",\"FromUserName\":\"oegRb5uO91RtXcc148bnJxEdpALo\",\"CreateTime\":123213213213213,\"MsgType\":\"text\",\"Content\":\"600460\",\"MsgId\":2321321321321321}";
            string url = string.Format(@"http://zjstock.free.aeert.com/api/GetTextMessage");
            //string url = string.Format(@"http://localhost:18768/api/GetAuthorize");
            _ = HttpUtils.PostAsync(message, url, "");



        }


    }
}
